<?php

namespace App\Http\Controllers;

use App\Actions\Web\UserAction;
use App\Actions\Web\UserLogAction;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Traits\WebResponse;
use Dcat\Admin\Admin;
use Dcat\Admin\Layout\Content;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    use WebResponse;

    protected $redirectToSessionKey = 'app_redirect_to';

    public function sso_login_callback(Request $request)
    {
        $message = '登录失败，如有问题，请联系管理员';
        $cas_host = "passport.ustc.edu.cn";
        $cas_port = 443;
        $cas_context = "";
        $url = route("auth.sso.login");
        // \phpCAS::setDebug(storage_path('logs/phpcas.log'));
        \phpCAS::client(CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context,$url);
        \phpCAS::setFixedServiceURL($url);
        \phpCAS::setNoCasServerValidation();


        if(\phpCAS::forceAuthentication()===true){
            $user = \phpCAS::getUser();
            $attributes = \phpCAS::getAttributes();

            \Log::debug('前端sso return', $attributes);
            if(isset($attributes['gid']) && $attributes['gid'] != ''){
                return $this->afterLogin($attributes, true);
            }
        }
        return redirect(route('auth.error'))->with('message', $message);
    }

    /**
     * 选择登录方式
     */
    public function get_local_login(Request $request, Content $content)
    {
        $url_previours = url()->previous();
        if (config('sso.is_enable')) {
            # 统一身份认证登录
            $caslogin = 'https://passport.ustc.edu.cn/login?service='. route('auth.sso.login').'&renew=true';
            return redirect($caslogin);
        }
        if (Auth::guard()->check()) {
            return redirect(route('home'));
        }
        // return $content->full()->body(view($this->view));
        // return view($this->view_dir.'.auth.login_select');
        return view("{$this->view_dir}.auth.login");
    }

    /**
     * GET 账号密码登录
     */
    public function loginByAccount(Request $request)
    {
        if (Auth::guard()->check()) {
            return redirect(route('home'));
        }
        return view("{$this->view_dir}.auth.login");
    }

    /**
     * POST 账号密码登录
     */
    public function post_local_login(Request $request)
    {
        if (config('sso.is_enable')) {
            exit('Not allowed');
        }

        $data = $request->all();
        if (!$data['username'] || !$data['password']) {
            return back()->withInput()->withErrors([
                'username' => '账号或者密码必填'
            ]);
        }
        $user = User::where('zjhm', $data['username'])->first();
        if (!$user) {
            return back()->withInput()->withErrors([
                'username' => '用户不存在'
            ]);
        }

       $hashedValue = '$2y$10$Wv37wKTUEduejRRhl1iQWeEPttyGinf/tNAfiDDKW/m3gQt0FF5rC';//gongyu*1110
    //    $hashedValue = $user->password;
        if (!Hash::check($request->password, $hashedValue)) {
            return back()->withInput()->withErrors([
                'username' => '账号或者密码错误'
            ]);
        }
        $attributes = $request->all();
        $login_result = $this->afterLogin($attributes, false);
        if (isset($login_result['status']) && $login_result['status'] == 'error') {
            return back()->withInput()->withErrors([
                'username' => $login_result['message']
            ]);
        }
        return redirect($login_result['data']['url']);
    }

    private function afterLogin($attributes, $is_sso = false)
    {
        if ((isset($attributes['gid']) && $attributes['gid'])) {
            $user = User::findByGid($attributes['gid']);
            if (!$user) {
                # 创建新用户
                try {
                    $user = UserAction::make()->register($attributes);
                } catch (\Throwable $th) {
                    return redirect(route('auth.sso_logout_witherror'))->with('message', $th->getMessage());
                }
            }
        } else if (isset($attributes['username']) && $attributes['username']) {
            $user = User::where('zjhm', $attributes['username'])->first();
        } else {
            exit('error');
        }

        if (!$user) {
            return $is_sso ? redirect(route('auth.sso_logout_witherror'))->with('message', '用户不存在') : $this->failed('用户不存在');
        }

        request()->session()->regenerate();
        Auth::guard()->login($user);
        try {
            UserLogAction::make(null, $user)->login()->log();
        } catch (\Throwable $th) {
            //throw $th;
        }
        return $is_sso ? redirect($this->redirectTo($user)) : $this->success(['url' => $this->redirectTo($user)]);
    }

    public function redirectTo($user = null)
    {
        $request = app(Request::class);
        if ($request->session()->has($this->redirectToSessionKey)) {
            $redirectTo = $request->session()->get($this->redirectToSessionKey);
            $request->session()->forget($this->redirectToSessionKey);
        } else {
            $redirectTo = route('home');
        }
        return $redirectTo;
    }

    public function logout(Request $request)
    {
        $message = '正在退出...';
        if ($request->session()->has('message')) {
            $message = $request->session()->get('message');
        }
        $request->session()->flash('message', $message);
        $caslogout_route = route('auth.sso.logout');
        $logout_route = route('auth.local.logout');
        return view($this->view_dir.'.auth.logout', compact('caslogout_route', 'logout_route'));
    }

    /**
     * 本地退出
     *
     * @param Request $request
     */
    public function local_logout(Request $request)
    {
        if (Auth::guard()->check()) {
            Auth::guard()->logout();
        }
        return redirect(route('login'));
    }

    /**
     * sso 退出
     */
    public function sso_logout()
    {
        if (!config('sso.is_enable')) {
            exit;
        }

        $cas_host = "passport.ustc.edu.cn";
        $cas_port = 443;
        $cas_context = "";
        $url = config('app.url');
        \phpCAS::client(CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context,$url);
        \phpCAS::setNoCasServerValidation();
        \phpCAS::logout();
        \phpCAS::handleLogoutRequests();
        \phpCAS::forceAuthentication();
        exit;
    }

    public function login_test($gid)
    {
        $user = Auth::user();
        if ($user->gid == '9201703523') {
            $new_user = User::findByGidOrZjhm($gid);
            if ($new_user) {
                request()->session()->regenerate();
                Auth::guard()->login($new_user);
            }
        } else {
            exit('无权进入');
        }
        return redirect($this->redirectTo($new_user));
    }
}
